<template>
  <div class="alarm-control-container">
    <!-- 页面标题和系统状态 -->
    <el-row class="mb-4">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <div class="title-section">
                <span class="title">工位报警控制终端</span>
                <el-tag 
                  :type="connectionStatus.isConnected ? 'success' : 'danger'"
                  class="connection-status"
                >
                  {{ connectionStatus.isConnected ? '已连接' : '未连接' }}
                </el-tag>
              </div>
              <div class="area-selector">
                <el-select 
                  v-model="selectedAreaId" 
                  placeholder="选择区域" 
                  @change="onAreaChange"
                  size="large"
                >
                  <el-option 
                    v-for="area in areas" 
                    :key="area.id" 
                    :label="area.name" 
                    :value="area.id"
                  />
                </el-select>
              </div>
              <div class="header-actions">
                <el-button 
                  v-if="!connectionStatus.isConnected" 
                  type="success" 
                  @click="connectWebSocket"
                  :loading="isConnecting"
                >
                  连接系统
                </el-button>
                <el-button type="primary" @click="showDeviceDialog = true">
                  <el-icon><Plus /></el-icon>
                  添加设备
                </el-button>
                <el-button @click="refreshStatus">
                  <el-icon><Refresh /></el-icon>
                  刷新状态
                </el-button>
              </div>
            </div>
          </template>
          
          <!-- 当前区域信息 -->
          <div class="current-area-info" v-if="currentArea">
            <div class="area-title-large">{{ currentArea.name }}</div>
            <div class="area-stats">
              <div class="stat-item">
                <div class="stat-value">{{ currentAreaStats.total }}</div>
                <div class="stat-label">设备总数</div>
              </div>
              <div class="stat-item">
                <div class="stat-value text-success">{{ currentAreaStats.online }}</div>
                <div class="stat-label">在线设备</div>
              </div>
              <div class="stat-item">
                <div class="stat-value text-warning">{{ currentAreaStats.alarming }}</div>
                <div class="stat-label">报警设备</div>
              </div>
              <div class="stat-item">
                <div class="stat-value text-danger">{{ currentAreaStats.critical }}</div>
                <div class="stat-label">严重报警</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 当前区域设备显示 -->
    <el-row v-if="currentArea">
      <el-col :span="24">
        <el-card class="workstation-card">
          <template #header>
            <div class="workstation-header">
              <span class="workstation-title">{{ currentArea.name }} - 工位设备</span>
              <el-tag :type="getAreaStatusType(currentArea)" size="large">
                {{ getAreaStatusText(currentArea) }}
              </el-tag>
            </div>
          </template>
          
          <!-- 设备大屏显示 -->
          <div class="workstation-grid">
            <div 
              v-for="device in currentArea.devices" 
              :key="device.id"
              class="workstation-device"
              @click="showDeviceDetail(device)"
            >
              <!-- 设备编号 -->
              <div class="device-number">{{ device.deviceId }}</div>
              
              <!-- 三色灯显示 -->
              <div class="traffic-light-large">
                <div 
                  class="light-large red" 
                  :class="{ active: device.status === 'red', blinking: device.status === 'red' && device.isAlarming }"
                ></div>
                <div 
                  class="light-large yellow" 
                  :class="{ active: device.status === 'yellow', blinking: device.status === 'yellow' && device.isAlarming }"
                ></div>
                <div 
                  class="light-large green" 
                  :class="{ active: device.status === 'green' }"
                ></div>
              </div>
              
              <!-- 设备信息 -->
              <div class="device-info-large">
                <div class="device-name-large">{{ device.customName || device.name }}</div>
                <div class="device-status-large">{{ getStatusText(device.status) }}</div>
                <div class="device-time-large" v-if="device.lastAlarmTime">
                  {{ formatTime(device.lastAlarmTime) }}
                </div>
              </div>
              
              <!-- 报警指示器 -->
              <div v-if="device.isAlarming" class="alarm-indicator-large">
                <el-icon class="alarm-icon-large"><Bell /></el-icon>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 无区域选择提示 -->
    <el-row v-else>
      <el-col :span="24">
        <el-card>
          <div class="no-area-selected">
            <el-icon size="64" color="#ccc"><Warning /></el-icon>
            <p>请选择一个区域查看设备状态</p>
          </div>
        </el-card>
      </el-col>
    </el-row>



    <!-- 添加设备对话框 -->
    <el-dialog v-model="showDeviceDialog" title="添加设备" width="500px">
      <el-form :model="newDevice" label-width="100px">
        <el-form-item label="设备名称">
          <el-input v-model="newDevice.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="所属区域">
          <el-select v-model="newDevice.areaId" placeholder="请选择区域">
            <el-option 
              v-for="area in areas" 
              :key="area.id" 
              :label="area.name" 
              :value="area.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备编号">
          <el-input v-model="newDevice.deviceId" placeholder="请输入设备编号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDeviceDialog = false">取消</el-button>
        <el-button type="primary" @click="addDevice">确定</el-button>
      </template>
    </el-dialog>

    <!-- 设备详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="设备详情" width="600px">
      <div v-if="selectedDevice">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="设备名称">{{ selectedDevice.name }}</el-descriptions-item>
          <el-descriptions-item label="自定义名称">
            <el-input 
              v-model="deviceCustomName" 
              placeholder="输入自定义名称"
              @blur="updateDeviceCustomName"
              size="small"
            />
          </el-descriptions-item>
          <el-descriptions-item label="设备编号">{{ selectedDevice.deviceId }}</el-descriptions-item>
          <el-descriptions-item label="当前状态">
            <el-tag :type="getAlarmTypeColor(selectedDevice.status)">{{ getStatusText(selectedDevice.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="是否报警">
            <el-tag :type="selectedDevice.isAlarming ? 'danger' : 'success'">
              {{ selectedDevice.isAlarming ? '报警中' : '正常' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="最后报警时间">{{ selectedDevice.lastAlarmTime || '无' }}</el-descriptions-item>
          <el-descriptions-item label="在线状态">
            <el-tag :type="selectedDevice.online ? 'success' : 'danger'">
              {{ selectedDevice.online ? '在线' : '离线' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="mt-4">
          <div class="alarm-buttons">
            <el-button type="danger" @click="reportDeviceFault(selectedDevice)" size="large">
              <el-icon><Warning /></el-icon>
              设备故障
            </el-button>
            <el-button type="warning" @click="reportMaterialShortage(selectedDevice)" size="large">
              <el-icon><Box /></el-icon>
              物料短缺
            </el-button>
            <el-button type="info" @click="reportQualityIssue(selectedDevice)" size="large">
              <el-icon><DocumentChecked /></el-icon>
              质量问题
            </el-button>
            <el-button type="success" @click="clearFault(selectedDevice)" size="large">
              <el-icon><CircleCheck /></el-icon>
              故障清除
            </el-button>
          </div>
          <div class="device-actions">
            <el-button type="primary" @click="testDevice(selectedDevice)">测试设备</el-button>
            <el-button @click="resetDevice(selectedDevice)">重置状态</el-button>
            <el-button type="danger" @click="removeDevice(selectedDevice)">删除设备</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Bell, Warning, Box, DocumentChecked, CircleCheck } from '@element-plus/icons-vue'
import { useAlarmSystemStore } from '@/store/alarmSystem'
import alarmWebSocket from '@/utils/alarmWebSocket'

// 使用store
const alarmStore = useAlarmSystemStore()

// 响应式数据
const showDeviceDialog = ref(false)
const showDetailDialog = ref(false)
const selectedDevice = ref(null)
const isConnecting = ref(false)
const selectedAreaId = ref('')
const deviceCustomName = ref('')

// 从store获取数据
const areas = computed(() => alarmStore.areas)
const connectionStatus = computed(() => alarmStore.connectionStatus)
const currentArea = computed(() => {
  if (!selectedAreaId.value) return null
  return areas.value.find(area => area.id === selectedAreaId.value)
})
const currentAreaStats = computed(() => {
  if (!currentArea.value) return { total: 0, online: 0, alarming: 0, critical: 0 }
  const devices = currentArea.value.devices
  return {
    total: devices.length,
    online: devices.filter(d => d.online).length,
    alarming: devices.filter(d => d.isAlarming).length,
    critical: devices.filter(d => d.status === 'red').length
  }
})
const systemStats = computed(() => ({
  total: alarmStore.totalDevices,
  online: alarmStore.onlineDevices,
  alarming: alarmStore.alarmingDevices,
  critical: alarmStore.criticalAlarms,
  warning: alarmStore.warningAlarms
}))

// 新设备表单
const newDevice = reactive({
  name: '',
  areaId: '',
  deviceId: ''
})

// 方法
const getStatusText = (status) => {
  const statusMap = {
    red: '故障报警',
    yellow: '维护提醒',
    green: '正常运行',
    off: '离线'
  }
  return statusMap[status] || '未知'
}

const getAlarmTypeColor = (type) => {
  const colorMap = {
    red: 'danger',
    yellow: 'warning',
    green: 'success',
    off: 'info'
  }
  return colorMap[type] || 'info'
}

const getAreaStatusType = (area) => {
  const hasRed = area.devices.some(d => d.status === 'red')
  const hasYellow = area.devices.some(d => d.status === 'yellow')
  
  if (hasRed) return 'danger'
  if (hasYellow) return 'warning'
  return 'success'
}

const getAreaStatusText = (area) => {
  const hasRed = area.devices.some(d => d.status === 'red')
  const hasYellow = area.devices.some(d => d.status === 'yellow')
  
  if (hasRed) return '有故障'
  if (hasYellow) return '需维护'
  return '正常'
}

const formatTime = (timeStr) => {
  if (!timeStr) return ''
  return new Date(timeStr).toLocaleString()
}

const showDeviceDetail = (device) => {
  selectedDevice.value = device
  deviceCustomName.value = device.customName || ''
  showDetailDialog.value = true
}

// 区域切换方法
const onAreaChange = (areaId) => {
  selectedAreaId.value = areaId
  ElMessage.success(`已切换到区域: ${currentArea.value?.name}`)
}

// 更新设备自定义名字
const updateDeviceCustomName = () => {
  if (!selectedDevice.value) return
  
  // 更新设备的自定义名字
  const device = alarmStore.findDevice(selectedDevice.value.deviceId)
  if (device) {
    device.customName = deviceCustomName.value
    ElMessage.success('设备名称已更新')
  }
}

const addDevice = () => {
  if (!newDevice.name || !newDevice.areaId || !newDevice.deviceId) {
    ElMessage.warning('请填写完整的设备信息')
    return
  }
  
  const device = alarmStore.addDevice(newDevice.areaId, {
    name: newDevice.name,
    deviceId: newDevice.deviceId,
    type: 'assembly'
  })
  
  if (device) {
    // 重置表单
    Object.assign(newDevice, { name: '', areaId: '', deviceId: '' })
    showDeviceDialog.value = false
    
    ElMessage.success('设备添加成功')
  } else {
    ElMessage.error('设备添加失败')
  }
}

const testDevice = (device) => {
  // 发送测试命令到设备
  alarmWebSocket.sendDeviceCommand(device.deviceId, 'test', { type: 'alarm_test' })
  
  // 模拟测试设备
  alarmStore.updateDeviceStatus(device.deviceId, 'yellow', true, new Date().toISOString())
  ElMessage.success('设备测试完成')
}

const resetDevice = (device) => {
  // 发送重置命令到设备
  alarmWebSocket.sendDeviceCommand(device.deviceId, 'reset')
  
  // 更新设备状态
  alarmStore.updateDeviceStatus(device.deviceId, 'green', false)
  ElMessage.success('设备状态已重置')
}

const removeDevice = async (device) => {
  try {
    await ElMessageBox.confirm('确定要删除这个设备吗？', '确认删除', {
      type: 'warning'
    })
    
    const success = alarmStore.removeDevice(device.id)
    if (success) {
      showDetailDialog.value = false
      ElMessage.success('设备删除成功')
    } else {
      ElMessage.error('设备删除失败')
    }
  } catch {
    // 用户取消删除
  }
}

const refreshStatus = () => {
  // 请求所有设备状态更新
  alarmWebSocket.requestDeviceStatus()
  ElMessage.success('状态刷新请求已发送')
}

// 报警按钮方法
const reportDeviceFault = (device) => {
  // 发送设备故障报警
  alarmWebSocket.sendDeviceCommand(device.deviceId, 'alarm', { type: 'device_fault', message: '设备故障报警' })
  alarmStore.updateDeviceStatus(device.deviceId, 'red', true, new Date().toISOString())
  ElMessage.error('设备故障报警已发送')
}

const reportMaterialShortage = (device) => {
  // 发送物料短缺报警
  alarmWebSocket.sendDeviceCommand(device.deviceId, 'alarm', { type: 'material_shortage', message: '物料短缺报警' })
  alarmStore.updateDeviceStatus(device.deviceId, 'yellow', true, new Date().toISOString())
  ElMessage.warning('物料短缺报警已发送')
}

const reportQualityIssue = (device) => {
  // 发送质量问题报警
  alarmWebSocket.sendDeviceCommand(device.deviceId, 'alarm', { type: 'quality_issue', message: '质量问题报警' })
  alarmStore.updateDeviceStatus(device.deviceId, 'yellow', true, new Date().toISOString())
  ElMessage.warning('质量问题报警已发送')
}

const clearFault = (device) => {
  // 清除故障状态
  alarmWebSocket.sendDeviceCommand(device.deviceId, 'clear_fault')
  alarmStore.updateDeviceStatus(device.deviceId, 'green', false)
  ElMessage.success('故障已清除')
}

// WebSocket连接管理
const connectWebSocket = () => {
  if (isConnecting.value) return
  
  isConnecting.value = true
  alarmWebSocket.connect()
  
  setTimeout(() => {
    isConnecting.value = false
  }, 3000)
}

const disconnectWebSocket = () => {
  alarmWebSocket.disconnect()
  ElMessage.info('已断开WebSocket连接')
}

// 生命周期
onMounted(() => {
  // 初始化store
  alarmStore.initialize()
  
  // 连接WebSocket
  connectWebSocket()
  
  // 默认选择第一个区域
  if (areas.value.length > 0) {
    selectedAreaId.value = areas.value[0].id
  }
  
  console.log('工位报警控制终端已加载')
  console.log('系统统计:', systemStats.value)
})

onUnmounted(() => {
  // 断开WebSocket连接
  disconnectWebSocket()
})
</script>

<style scoped>
.alarm-control-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.connection-status {
  font-size: 12px;
}

.area-selector {
  flex: 1;
  max-width: 300px;
  margin: 0 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.current-area-info {
  text-align: center;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  margin-top: 15px;
  color: white;
}

.area-title-large {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 20px;
  text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
}

.area-stats {
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #666;
  font-weight: normal;
}

.text-success {
  color: #67c23a;
}

.text-warning {
  color: #e6a23c;
}

.text-danger {
  color: #f56c6c;
}

.workstation-card {
  margin-bottom: 20px;
}

.workstation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.workstation-title {
  font-size: 20px;
  font-weight: bold;
  color: #2c3e50;
}

.no-area-selected {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.no-area-selected p {
  margin-top: 20px;
  font-size: 18px;
}

.workstation-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 30px;
  padding: 30px 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.workstation-device {
  background: linear-gradient(145deg, #ffffff, #f0f0f0);
  border: 3px solid #e4e7ed;
  border-radius: 16px;
  padding: 30px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  min-height: 280px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.workstation-device:hover {
  border-color: #409eff;
  box-shadow: 0 12px 35px rgba(64, 158, 255, 0.2);
  transform: translateY(-5px);
}

.device-number {
  position: absolute;
  top: 15px;
  left: 20px;
  background: #409eff;
  color: white;
  padding: 5px 12px;
  border-radius: 20px;
  font-weight: bold;
  font-size: 14px;
}

.traffic-light-large {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-bottom: 20px;
}

.light-large {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 3px solid #ddd;
  opacity: 0.3;
  transition: all 0.3s ease;
}

.light-large.red {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.light-large.yellow {
  background-color: #e6a23c;
  border-color: #e6a23c;
}

.light-large.green {
  background-color: #67c23a;
  border-color: #67c23a;
}

.light-large.active {
  opacity: 1;
  box-shadow: 0 0 20px currentColor;
}

.light-large.blinking {
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0.3; }
}

.device-info-large {
  text-align: center;
  flex: 1;
}

.device-name-large {
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 10px;
  color: #2c3e50;
}

.device-status-large {
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.device-time-large {
  font-size: 12px;
  color: #999;
}

.alarm-indicator-large {
  position: absolute;
  top: 15px;
  right: 20px;
  color: #f56c6c;
}

.alarm-icon-large {
  font-size: 24px;
  animation: shake 0.5s infinite;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-2px); }
  75% { transform: translateX(2px); }
}

.alarm-buttons {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px dashed #e9ecef;
}

.alarm-buttons .el-button {
  height: 60px;
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.alarm-buttons .el-button .el-icon {
  font-size: 20px;
}

.device-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
}
</style>